from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.shortcuts import render_to_response
from django.contrib.auth.models import User

def login(request):
    if request.method == 'GET':
        return render_to_response("login.xhtml")
    if request.user.is_authenticated():
        return render_to_response("home.xhtml")
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    user = auth.authenticate(username=username, password=password)
    if user is not None and user.is_active:
        auth.login(request, user)
        #request.session['username'] = user.username
        #return render_to_response("home.xhtml", {'user', user})
        return HttpResponseRedirect('/accounts/home')
    else:
        return HttpResponse("Your username and password didn't match.")
    
    #try:
    #    m = User.objects.get(username=request.POST['username'])
    #    if m.password == request.POST['password']:
    #        request.session['user_id'] = m.id
    #        return HttpResponseRedirect("/accounts/home")
    #except User.DoesNotExist:
    #    return HttpResponse("Your username and password didn't match.")

def logout(request):
    auth.logout(request)
    return HttpResponseRedirect('/accounts/login')
    #try:
    #    del request.session['user_id']
    #except KeyError:
    #    pass
    #return HttpResponse("You're logged out.")

def home(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/accounts/login/?next=%s' % request.path)
    return render_to_response("home.xhtml", {'user': request.user})

def register(request):
    if request.method == 'POST':
    #    form = UserCreationForm(request.POST)
    #    if form.is_valid():
#            return HttpResponse("register success")
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        confirmpassword = request.POST.get('confirmpassword', '')
        email = request.POST.get('email', '')
        user = User.objects.create_user(username, email, password)
        user.save()
        return HttpResponse("register success")
            
    else:
    #    form = UserCreationForm()
    #return render_to_response("register.xhtml", {
    #    'form': form,
    #})
        return render_to_response("register.xhtml")